<?php 

	session_start();

	// check for login
	if(!isset($_SESSION['atbat']) && !isset($_COOKIE['remember_atbat'])) {

		// no login, move to index page
		header("Location: http://localhost/atbat/html/");

	}

	// connect to db
	require_once '../db/db.php';
	
	// load helper functions
	require_once 'include/functions.php';

	// get user id
	$sql = "SELECT user_id FROM users WHERE MD5(username) IN ('";
	$sql .= ((isset($_SESSION['atbat'])) ? $_SESSION['atbat'] : '') . "', '";
	$sql .= ((isset($_COOKIE['remember_atbat'])) ? $_COOKIE['remember_atbat'] : '') . "')";

	$id = $db->query($sql)->fetchAll();
	$user_id = $id[0]['user_id'];
	
	// get game info from url hash
	if(isset($_GET['id']) && $_GET['id'] != '') {
		
		// validate and sanitize game id
		if(filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
			
			$g_id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
			
			$sql = "SELECT game_details.away_team, CONCAT(t1.city, ' ', t1.name) AS 'away_team', game_details.home_team, CONCAT(t2.city, ' ', t2.name) AS 'home_team' FROM game_details LEFT JOIN teams AS t1 ON t1.team_id = game_details.away_team LEFT JOIN teams AS t2 ON t2.team_id = game_details.home_team WHERE game_details.game_id = " . $g_id;
			
			try {
				
				$stmt = $db->prepare($sql);
				$stmt->execute();
								
				// bind column names
				$stmt->bindColumn(1, $away_team_id);
				$stmt->bindColumn(2, $away_team);
				$stmt->bindColumn(3, $home_team_id);
				$stmt->bindColumn(4, $home_team);
				
				$stmt->fetch(PDO::FETCH_BOUND);
				
			} catch(PDOException $e) {
				
				$message[] = '<p class="error">DB Error: ' . $e->getMessage() . '</p>';
				$error = true;	
				
			}
			
		}else{
			
			// invalid game id
			header("Location: http://localhost/atbat/html/new-game");
			
		}
		
	}else{
		
		// no id in url hash
		header("Location: http://localhost/atbat/html/new-game");
		
	}
	
	// process roster choices
	if(isset($_POST['setRosters'])) {
		
		// sanitize and validate data
		$error = false;
		
		// away team
		if(isset($_POST['away_team']) && $_POST['away_team'] != '') {
			
			if(filter_var($_POST['away_team'], FILTER_VALIDATE_INT)) {
				
				$away_team = filter_var($_POST['away_team'], FILTER_SANITIZE_NUMBER_INT);	
				
			}else{
				
				$message[] = '<p class="error">Invalid Away Team.</p>';
				$error = true;
				
			}
			
		}else{
			
			$message[] = '<p class="error">Please choose a roster for the away team.</p>';
			$error = true;
			
		}
		
		// home team
		if(isset($_POST['home_team']) && $_POST['home_team'] != '') {
			
			if(filter_var($_POST['home_team'], FILTER_VALIDATE_INT)) {
				
				$home_team = filter_var($_POST['home_team'], FILTER_SANITIZE_NUMBER_INT);	
				
			}else{
				
				$message[] = '<p class="error">Invalid Home Team.</p>';
				$error = true;
				
			}
			
		}else{
			
			$message[] = '<p class="error">Please choose a roster for the home team.</p>';
			$error = true;
			
		}
		
		// save roster data and start scoring game
		if($error == false) {
			
			$sql = "UPDATE game_details SET away_roster = " . $away_team . ", home_roster = " . $home_team . " WHERE game_id = " . $g_id;
			$db->exec($sql);
			
			header("Location: http://localhost/atbat/html/score-game/" . $g_id);
				
		}
		
	}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="http://localhost/atbat/html/" />
	<meta charset="utf-8">
	<title>AtBat :: Score a New Game</title>
	<meta name="description" content="">
	<meta name="author" content="Sean Mullin, http://parametercontraption.com">
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
	<link rel="shortcut icon" href="images/design/favicon.ico">
	<link rel="apple-touch-icon" href="images/design/apple-touch-icon.png">
	<link rel="stylesheet" href="css/screen.css"><link rel="stylesheet" media="all" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/themes/base/jquery-ui.css">
    <script src="js/modernizr-1.5.min.js"></script>
</head>
<body>
	<?php require_once 'include/header.html'; ?>
    <section id="content">
        <h1>Start a New Game</h1>
    	<form id="gameForm" method="post" action="choose-roster/<?php echo $g_id; ?>">
        	<?php if(isset($message)) foreach($message as $m) print $m; ?>
        	<fieldset>
            	<legend>Choose a Roster For Each Team</legend>
                <p>
                	<label for="away_team"><?php echo $away_team; ?>:</label>
                    <select name="away_team" id="away_team" required>
                    	<option value="0">Choose One</option>
                    	<?php
						
							// loop thru this user's rosters
							// provide dialog to create roster/add players on the fly
							$sql = "SELECT roster_id, nickname FROM rosters WHERE user_id IN (" . $user_id . ", 0) AND team_id = " . $away_team_id;
							foreach($db->query($sql) as $r) {

								print '<option value="' . $r['roster_id'] . '">' . $r['nickname'] . '</option>';

							}
												
						?>
                        <option value="">Create a New Roster</option>
                    </select>
                </p>          		
                <p>
                	<label for="home_team"><?php echo $home_team; ?>:</label>
                    <select name="home_team" id="home_team" required>
                    	<option value="0">Choose One</option>
                    	<?php
						
							// loop thru this user's rosters
							// provide dialog to create roster/add players on the fly
							$sql = "SELECT roster_id, nickname FROM rosters WHERE user_id IN (" . $user_id . ", 0) AND team_id = " . $home_team_id;
							foreach($db->query($sql) as $r) {

								print '<option value="' . $r['roster_id'] . '">' . $r['nickname'] . '</option>';

							}
												
						?>
                        <option value="">Create a New Roster</option>
                    </select>
                </p>
                <input type="submit" name="setRosters" id="setRosters" value="Set Rosters" />
            </fieldset>
        </form>
    </section>
    <?php require_once 'include/footer.html'; ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
    <script>
    	$(document).ready(function() {	
			// set home and away vars
			var away_team = <?php echo $away_team_id; ?>;
			var home_team = <?php echo $home_team_id; ?>;
			var team;
			
			$("#away_team").change(function() { // listen for change on roster input
				// show roster form
				if($(this).val() == '') {
					team = away_team;
					$("#dialogRosterAway").dialog("open");
				}
			});
			
			$("#home_team").change(function() { // listen for change on roster input
				// show roster form
				if($(this).val() == '') {
					team = home_team;
					$("#dialogRosterHome").dialog("open");
				}
			});
			
			// new roster dialog
			$("#dialogRosterAway").dialog({
				autoOpen: false,
				width: 648,
				modal: true,
				draggable: false,
				resizable: false,
				buttons: {
					"Create Roster": function() {
						$.post(
							"create-roster.php",
							{
								team_id: team,
								game_id: <?php echo $g_id; ?>,
								nickname: $("#nickname_away").val(),
								createRoster: $("#createRosterAway").val(),
								addPlayers: $("#addPlayersAway").val(),
								players: $(".players_away").serializeArray()
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialogRosterAway").prepend(data);
								if($(data).hasClass('success')) {
									// set value of roster select input
									var select_id = $(data).attr("rel");
									var select_title = $(data).attr("title");
									$("#away_team").append('<option value="' + select_id + '" selected>' + select_title + '</option>');
									// close window after 2.5 seconds on success
									setTimeout(function() { $("#dialogRosterAway").dialog("close"); }, 2500);
								}								
							}
						);
					},
					Cancel: function() { $(this).dialog("close"); }
				}
			});
			
			// new roster dialog
			$("#dialogRosterHome").dialog({
				autoOpen: false,
				width: 648,
				modal: true,
				draggable: false,
				resizable: false,
				buttons: {
					"Create Roster": function() {
						$.post(
							"create-roster.php",
							{
								team_id: team,
								game_id: <?php echo $g_id; ?>,
								nickname: $("#nickname_home").val(),
								createRoster: $("#createRosterHome").val(),
								addPlayers: $("#addPlayersHome").val(),
								players: $(".players_home").serializeArray()
							},
							function(data) {
								$(".error").remove();
								$(".success").remove();
								$(".notice").remove();
								$("#dialogRosterHome").prepend(data);
								if($(data).hasClass('success')) {
									// set value of roster select input
									var select_id = $(data).attr("rel");
									var select_title = $(data).attr("title");
									$("#home_team").append('<option value="' + select_id + '" selected>' + select_title + '</option>');
									// close window after 2.5 seconds on success
									setTimeout(function() { $("#dialogRosterHome").dialog("close"); }, 2500);
								}								
							}
						);
					},
					Cancel: function() { $(this).dialog("close"); }
				}
			});
		});
    </script>
    <fieldset id="dialogRosterAway" title="Create a New Roster">
        <input type="hidden" name="createRosterAway" id="createRosterAway" value="1" />
        <input type="hidden" name="addPlayersAway" id="addPlayersAway" value="1" />
        <p><label for="nickname_away">Roster Nickname:</label><input type="text" name="nickname_away" id="nickname_away" required /></p>
        <p><label for="players">Players:</label></p>
       	<?php for($i = 1; $i <= 9; $i++) { ?>
        <p>
            <label><?php echo $i; ?>:</label>
            <select name="players[]" class="players_away">
			<?php
            
                // loop thru and show all this user's players
                $sql = "SELECT player_id, name FROM players WHERE user_id IN (" . $user_id . ", 0) AND team_id = " . $away_team_id;
                foreach($db->query($sql) as $p) {
                    
                    print '<option value="' . $p['player_id'] . '">' . $p['name'] . '</option>';	
                    
                }
                
            ?>
            </select>
        </p>
    <?php } ?>
    </fieldset>
    <fieldset id="dialogRosterHome" title="Create a New Roster">
        <input type="hidden" name="createRosterHome" id="createRosterHome" value="1" />
        <input type="hidden" name="addPlayersHome" id="addPlayersHome" value="1" />
        <p><label for="nickname_home">Roster Nickname:</label><input type="text" name="nickname_home" id="nickname_home" required /></p>
        <p><label for="players">Players:</label></p>
       	<?php for($i = 1; $i <= 9; $i++) { ?>
        <p>
            <label><?php echo $i; ?>:</label>
            <select name="players[]" class="players_home">
			<?php
            
                // loop thru and show all this user's players
                $sql = "SELECT player_id, name FROM players WHERE user_id IN (" . $user_id . ", 0) AND team_id = " . $home_team_id;
                foreach($db->query($sql) as $p) {
                    
                    print '<option value="' . $p['player_id'] . '">' . $p['name'] . '</option>';	
                    
                }
                
            ?>
            </select>
        </p>
    <?php } ?>
    </fieldset>
</body>
</html>